<template>
    <div>
        <el-upload ref="uploadRef" :auto-upload="false" :on-change="handleChange" style="width: 100%"
            :file-list="fileList" v-if="roleType !== 3">
            <el-button class="ml-3" type="primary">选择就业Excel数据</el-button>
        </el-upload>
        <el-table :data="filteredCompanies" style="width: 100%">
            <el-table-column prop="title" label="公司名称">
                <template #header>
                    <el-input v-model="company" size="small" placeholder="输入公司名称搜索" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="primary" round
                        @click="handleOpenPreviewDialog(scope.row)">面试题</el-button>
                    <el-button size="small" type="warning" round @click="handleOpenEditDialog(scope.row)"
                        v-if="roleType !== 3">更新题库</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog v-model="editDialogVisible" title="更新题库" width="80%">
            <editor @updateEditorEvent="handleUpdateEditorEvent" :content="curItem.question" v-if="editDialogVisible">
            </editor>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSaveForm">保存</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="previewDialogVisible" title="预览题库" width="80%">
            <!-- 双大括号插值语法不会解析html，防止xss的攻击问题，需要使用v-html属性来实现html代码片段的插入 -->
            <!-- <div>{{ curItem.question }}</div> -->
            <el-card v-html="curItem.question" shadow="never"></el-card>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import Editor from '../../components/editor/Editor.vue'

import importExcel from '../../util/ImportExcel'
import axios from 'axios'

import useUserStore from '../../store/useUserStore'

const { user: { username, role: { roleType } } } = useUserStore()

const fileList = ref([])
const companies = ref([])
const employments = ref([])
const company = ref('')
const editDialogVisible = ref(false)
const previewDialogVisible = ref(false)
let curItem = {}

const filteredCompanies = computed(() => companies.value.filter(({ title }) => title.toLowerCase().includes(company.value.toLowerCase())))

const handleChange = (e) => {
    // console.log(e)
    importExcel(e.raw, async (data) => {
        // console.log(data)
        fileList.value = []
        // 存储公司数据
        const companies = data.map(({ company }) => ({ title: company }))
        await addCompanies(companies)

        // TODO 存储学生就业数据
        await addEmployments(data)

        await getCompanies()
    })
}

const addCompanies = async (companies) => {
    var res = await axios.post('/adminapi/companies', companies)

    if (res.statusText === 'OK') {
        ElMessage({
            message: '学生就业数据导入成功',
            type: 'success'
        })
    } else {
        ElMessage({
            message: '学生就业数据添加失败',
            type: 'error'
        })
    }
}

const addEmployments = async (employments) => {
    var res = await axios.post('/adminapi/employments', employments)

    if (res.statusText === 'OK') {
        ElMessage({
            message: '公司数据导入成功',
            type: 'success'
        })
    } else {
        ElMessage({
            message: '公司数据添加失败',
            type: 'error'
        })
    }
}

const getCompanies = async () => {
    var res = await axios.get('/adminapi/companies')
    // console.log(res.data)
    companies.value = res.data
}

onMounted(async () => await getCompanies())

const handleOpenEditDialog = (item) => {
    curItem = item
    editDialogVisible.value = true
}

const handleOpenPreviewDialog = (item) => {
    curItem = item
    previewDialogVisible.value = true
}

const handleSaveForm = async () => {
    editDialogVisible.value = false
    var res = await axios.put(`/adminapi/companies/${curItem._id}`, curItem)
    if (res.statusText === 'OK') {
        ElMessage({
            message: '保存成功',
            type: 'success'
        })
        await getCompanies()
    } else {
        ElMessage({
            message: '保存失败',
            type: 'error'
        })
    }
}

const handleUpdateEditorEvent = (data) => {
    console.log(data)
    curItem['question'] = data
}
</script>